package com.example.shutdown_v1.controller;

import com.example.shutdown_v1.entity.Gateway;
import com.example.shutdown_v1.repository.GatewayRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 网关管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/gateway")
@RequiredArgsConstructor
public class GatewayController {
    
    private final GatewayRepository gatewayRepository;
    
    /**
     * 注册新网关
     */
    @PostMapping("/register")
    public ResponseEntity<?> register(@RequestBody Map<String, String> request) {
        try {
            String gatewayMac = request.get("gatewayMac");
            String gatewayTopic = request.get("gatewayTopic");
            String shopIdStr = request.get("shopId");
            
            // 检查必填字段
            if (gatewayMac == null || gatewayTopic == null) {
                return ResponseEntity.badRequest().body(Map.of(
                    "success", false,
                    "message", "参数不完整：gatewayMac, gatewayTopic 为必填项"
                ));
            }
            
            // 检查是否已存在
            Optional<Gateway> existing = gatewayRepository.findByGatewayMac(gatewayMac);
            if (existing.isPresent()) {
                return ResponseEntity.badRequest().body(Map.of(
                    "success", false,
                    "message", "该网关MAC地址已存在"
                ));
            }
            
            // 创建网关
            Gateway gateway = new Gateway();
            gateway.setGatewayMac(gatewayMac);
            gateway.setGatewayTopic(gatewayTopic);
            gateway.setPublishTopic(gatewayTopic);  // 发布主题和网关主题一致
            gateway.setShopId(shopIdStr != null ? Long.parseLong(shopIdStr) : null);
            gateway.setStatus((byte) 1);
            gateway.setRegisterTime(LocalDateTime.now());
            gateway.setRemark(request.get("remark"));
            
            gatewayRepository.save(gateway);
            
            log.info("网关注册成功: MAC={}, Topic={}, ShopId={}", gatewayMac, gatewayTopic, gateway.getShopId());
            
            return ResponseEntity.ok(Map.of(
                "success", true,
                "message", "网关注册成功",
                "gateway", gateway
            ));
            
        } catch (Exception e) {
            log.error("网关注册失败", e);
            return ResponseEntity.internalServerError().body(Map.of(
                "success", false,
                "message", "注册失败：" + e.getMessage()
            ));
        }
    }
    
    /**
     * 查询所有网关
     */
    @GetMapping("/list")
    public ResponseEntity<?> listAll() {
        try {
            List<Gateway> gateways = gatewayRepository.findAll();
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("gateways", gateways);
            response.put("count", gateways.size());
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("查询网关列表失败", e);
            return ResponseEntity.internalServerError().body(Map.of(
                "success", false,
                "message", "查询失败：" + e.getMessage()
            ));
        }
    }
    
    /**
     * 根据主题查询网关详情
     */
    @GetMapping("/topic/{topic}")
    public ResponseEntity<?> getByTopic(@PathVariable String topic) {
        try {
            Optional<Gateway> gatewayOpt = gatewayRepository.findByGatewayTopic(topic);
            
            if (!gatewayOpt.isPresent()) {
                return ResponseEntity.ok(Map.of(
                    "success", false,
                    "message", "未找到该网关"
                ));
            }
            
            return ResponseEntity.ok(Map.of(
                "success", true,
                "gateway", gatewayOpt.get()
            ));
            
        } catch (Exception e) {
            log.error("查询网关失败", e);
            return ResponseEntity.internalServerError().body(Map.of(
                "success", false,
                "message", "查询失败：" + e.getMessage()
            ));
        }
    }
    
    /**
     * 更新网关信息
     */
    @PutMapping("/update/{id}")
    public ResponseEntity<?> update(@PathVariable Long id, @RequestBody Map<String, String> request) {
        try {
            Optional<Gateway> gatewayOpt = gatewayRepository.findById(id);
            
            if (!gatewayOpt.isPresent()) {
                return ResponseEntity.ok(Map.of(
                    "success", false,
                    "message", "网关不存在"
                ));
            }
            
            Gateway gateway = gatewayOpt.get();
            
            // 更新允许的字段
            if (request.containsKey("shopId")) {
                gateway.setShopId(Long.parseLong(request.get("shopId")));
            }
            if (request.containsKey("remark")) {
                gateway.setRemark(request.get("remark"));
            }
            if (request.containsKey("status")) {
                gateway.setStatus(Byte.parseByte(request.get("status")));
            }
            
            gatewayRepository.save(gateway);
            
            return ResponseEntity.ok(Map.of(
                "success", true,
                "message", "更新成功",
                "gateway", gateway
            ));
            
        } catch (Exception e) {
            log.error("更新网关失败", e);
            return ResponseEntity.internalServerError().body(Map.of(
                "success", false,
                "message", "更新失败：" + e.getMessage()
            ));
        }
    }
    
    /**
     * 删除网关
     */
    @DeleteMapping("/delete/{id}")
    public ResponseEntity<?> delete(@PathVariable Long id) {
        try {
            if (!gatewayRepository.existsById(id)) {
                return ResponseEntity.ok(Map.of(
                    "success", false,
                    "message", "网关不存在"
                ));
            }
            
            gatewayRepository.deleteById(id);
            
            return ResponseEntity.ok(Map.of(
                "success", true,
                "message", "删除成功"
            ));
            
        } catch (Exception e) {
            log.error("删除网关失败", e);
            return ResponseEntity.internalServerError().body(Map.of(
                "success", false,
                "message", "删除失败：" + e.getMessage()
            ));
        }
    }
    
    /**
     * 查询在线网关
     */
    @GetMapping("/online")
    public ResponseEntity<?> listOnline() {
        try {
            List<Gateway> gateways = gatewayRepository.findByStatus((byte) 1);
            
            return ResponseEntity.ok(Map.of(
                "success", true,
                "gateways", gateways,
                "count", gateways.size()
            ));
            
        } catch (Exception e) {
            log.error("查询在线网关失败", e);
            return ResponseEntity.internalServerError().body(Map.of(
                "success", false,
                "message", "查询失败：" + e.getMessage()
            ));
        }
    }
}

